package org.jeecg.modules.demo.drfusers.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.jeecg.common.system.query.QueryGenerator;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.drfAdmin.entity.DrfAdmin;
import org.jeecg.modules.demo.drfAdmin.service.IDrfAdminService;
import org.jeecg.modules.demo.drfStudent.entity.DrfStudent;
import org.jeecg.modules.demo.drfStudent.service.IDrfStudentService;
import org.jeecg.modules.demo.drfTecher.entity.DrfTeacher;
import org.jeecg.modules.demo.drfTecher.service.IDrfTeacherService;
import org.jeecg.modules.demo.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.demo.constant.JwtClaimsConstant;
import org.jeecg.modules.demo.drfusers.entity.DrfUsers;
import org.jeecg.modules.demo.drfusers.service.IDrfUsersService;

/**
 * @Description: 用户表
 * @Author: jeecg-boot
 * @Date:   2025-10-02
 * @Version: V1.0
 */
@Api(tags = "盲审—用户表")
@RestController
@RequestMapping("/drf/Users")
@Slf4j
public class DrfUsersController extends JeecgController<DrfUsers, IDrfUsersService> {
	@Autowired
	private IDrfUsersService drfUsersService;
	@Autowired
	private JwtProperties jwtProperties;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private IDrfStudentService drfStudentService;
	@Autowired
	private IDrfTeacherService drfTeacherService;
	@Autowired
	private IDrfAdminService drfAdminService;

	/**
	 * 分页列表查询
	 *
	 * @param drfUsers
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "用户表-分页列表查询")
	@ApiOperation(value="用户表-分页列表查询", notes="用户表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DrfUsers>> queryPageList(DrfUsers drfUsers,
												 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												 HttpServletRequest req) {
        QueryWrapper<DrfUsers> queryWrapper = QueryGenerator.initQueryWrapper(drfUsers, req.getParameterMap());
		Page<DrfUsers> page = new Page<DrfUsers>(pageNo, pageSize);
		IPage<DrfUsers> pageList = drfUsersService.page(page, queryWrapper);
		return Result.success(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param drfUsers
	 * @return
	 */
	@AutoLog(value = "用户表-添加")
	@ApiOperation(value="用户表-添加", notes="用户表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DrfUsers drfUsers) {
		drfUsersService.save(drfUsers);
		//根据权限来添加对应的信息
		if(drfUsers.getStatus().equals("student")){
			DrfStudent drfStudent = new DrfStudent();
			drfStudent.setUserId(drfUsers.getId());
			drfStudent.setName(drfUsers.getRealName());
			drfStudent.setStudentId(drfUsers.getUsername());
			drfStudentService.save(drfStudent);
		}else if(drfUsers.getStatus().equals("teacher")){
			DrfTeacher drfTeacher = new DrfTeacher();
			drfTeacher.setUserId(drfUsers.getId());
			drfTeacher.setName(drfUsers.getRealName());
			drfTeacher.setTeacherId(drfUsers.getUsername());
			drfTeacherService.save(drfTeacher);
		}else if(drfUsers.getStatus().equals("admin")){
			DrfAdmin drfAdmin = new DrfAdmin();
			drfAdmin.setUserId(drfUsers.getId());
			drfAdmin.setName(drfUsers.getRealName());
			drfAdmin.setAdminId(drfUsers.getUsername());
			drfAdminService.save(drfAdmin);
		}
		return Result.success("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param drfUsers
	 * @return
	 */
	@AutoLog(value = "用户表-编辑")
	@ApiOperation(value="用户表-编辑", notes="用户表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DrfUsers drfUsers) {
		drfUsersService.updateById(drfUsers);
		return Result.success("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "用户表-通过id删除")
	@ApiOperation(value="用户表-通过id删除", notes="用户表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		drfUsersService.removeById(id);
		return Result.success("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "用户表-批量删除")
	@ApiOperation(value="用户表-批量删除", notes="用户表-批量删除")
	@Transactional
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) List<String> ids) {
		for(String id:ids){
			DrfUsers user = drfUsersService.getById(id);
			log.info("删除用户id:{}",id);
			if(user == null) {
				continue; // 如果用户不存在，跳过处理
			}
			if(user.getStatus().equals("student")){
				drfStudentService.removeById(id);
			}else if(user.getStatus().equals("teacher")){
				drfTeacherService.removeById(id);
			} else if (user.getStatus().equals("admin")) {
				drfAdminService.removeById(id);
			}
		}
		this.drfUsersService.removeByIds(ids);
		return Result.success("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "用户表-通过id查询")
	@ApiOperation(value="用户表-通过id查询", notes="用户表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DrfUsers> queryById(@RequestParam(name="id",required=true) String id) {
		DrfUsers drfUsers = drfUsersService.getById(id);
		if(drfUsers==null) {
			return Result.error("未找到对应数据");
		}
		return Result.success(drfUsers);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param drfUsers
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DrfUsers drfUsers) {
        return super.exportXls(request, drfUsers, DrfUsers.class, "用户表");
    }

    /**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public org.jeecg.common.api.vo.Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DrfUsers.class);
    }

	/**
	 * 用户登录
	 */
	@ApiOperation(value = "用户登录", notes = "用户登录")
	@PostMapping("/login")
	public Result<UserVO> login(@RequestBody UserDTO userDTO, HttpServletRequest request) {

		log.info("用户登录：");

		//获取验证码
		String storedCode = redisTemplate.opsForValue().get(request.getRemoteAddr());
		//消除验证码空格
		userDTO.setCaptcha(userDTO.getCaptcha().trim());

		// 验证码校验
		if(storedCode == null || !storedCode.equalsIgnoreCase(userDTO.getCaptcha())){
			log.info("验证码错误" + storedCode);
			return Result.error("验证码错误");
		}

		// 使用MP根据用户名与密码查询
		QueryWrapper<DrfUsers> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", userDTO.getUsername());
		queryWrapper.eq("password", userDTO.getPassword());
		DrfUsers user = drfUsersService.getOne(queryWrapper);
		if (user == null) {
			return Result.error("用户名或密码错误");
		}
		log.info("用户登录成功：{}", user.getId());
		//登录成功后删除验证码
		redisTemplate.delete(request.getRemoteAddr());

		
		// 登录成功后，生成jwt令牌
		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.USER_ID, user.getId());
		String token = drfJwtUtil.createJWT(
				jwtProperties.getUserSecretKey(),
				jwtProperties.getUserTtl(),
				claims);
		log.info("生成jwt令牌：{}", token);
		// 登录成功,构建用户信息
		UserVO userVO = UserVO.builder()
				.id(user.getId())
				.name(user.getRealName())
				.Status(user.getStatus())
				.token(token)
				.build();
		return Result.success(userVO);
	}

	/**
	 * 获取验证码
	 */

	@ApiOperation("获取验证码")
	@GetMapping("/captcha")
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置响应头
		response.setContentType("image/png");
		response.setCharacterEncoding("UTF-8");

		
		// 获取验证码
		LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 40);

		// 设置验证码内容与输出到http响应
		String code = captcha.getCode();

		// 将验证码保存到redis中，以ip地址为key，有效期60秒
		//存入前删除空格
		code = code.replaceAll("\\s", "");
		redisTemplate.opsForValue().set( request.getRemoteAddr(), code, 60, TimeUnit.SECONDS);

		// 写入响应
		captcha.write(response.getOutputStream());
		
		// 输出验证码到控制台
		log.info("验证码：" + code);
	}

	/**
	 * 更改密码
	 */
	@ApiOperation("更改密码")
	@PostMapping("/passwordChange")
	public Result<String> passwordChange(@RequestBody PasswordChangeDTO passwordChangeDTO) {
		//根据用户名与原密码查询用户
		QueryWrapper<DrfUsers> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", passwordChangeDTO.getUsername());
		queryWrapper.eq("password", passwordChangeDTO.getOldPassword());
		DrfUsers user = drfUsersService.getOne(queryWrapper);
		if (user == null) {
			return Result.error("用户名或密码错误");
		}
		if(passwordChangeDTO.getNewPassword().equals(passwordChangeDTO.getOldPassword())) {
			return Result.error("新密码不能与原密码相同");
		}else if (!passwordChangeDTO.getNewPassword().equals(passwordChangeDTO.getConfirmPassword())){
			return Result.error("两次输入密码不一致");
		}else {
			user.setPassword(passwordChangeDTO.getNewPassword());
			drfUsersService.updateById(user);
			return Result.success("密码修改成功");
		}
	}

	/**
	 * 用户退出
	 */
	@ApiOperation("用户退出")
	@GetMapping("/logout")
	public Result<String> logout() {
		return Result.success("用户退出成功");
	}
}